﻿using Castle.Core.Logging;
using IdentityServer4.Extensions;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using ZFY.AspNetCore;
using ZFY.Core;

using ZFY.UMC.Identity.Model.User;
using ZFY.UMC.API.Model;

namespace ZFY.UMC.Identity.Controllers.User
{
    public class UserController : BaseController
    {
        private readonly UserManager<UMC.API.Model.User> _userManager;
        private readonly ILogger<UserController> _logger;
        private readonly SignInManager<UMC.API.Model.User> _signInManager;
        private readonly AccountController _accountController;

        public UserController(UserManager<UMC.API.Model.User> userManager, ILogger<UserController> logger, SignInManager<UMC.API.Model.User> signInManager,AccountController accountController)
        {
            _userManager = userManager;
            _logger = logger;
            _signInManager = signInManager;
            _accountController = accountController;
        }



        public IActionResult Index()
        {
            return View();
        }
        [HttpGet]
        public IActionResult ChangePassword()
        {
            return View();
        }
        [HttpPut]
        public async Task<IActionResult> ChangePassword([FromBody] ChangePasswordInput input)
        {
            var user = await _userManager.FindByIdAsync(HttpContext.User.GetSubjectId());

            if (user is null)
            {
                throw new ZFYException("用户不存在");
            }

            var result = await _userManager.ChangePasswordAsync(user, input.OldPassword, input.NewPassword);

            if (result.Succeeded)
            {
                _logger.LogInformation("User created a new account with password.");

                await _signInManager.SignOutAsync();

                return Json($"/account/login?returnUrl={input.ReturnUrl}".GetReponse(true));

            }
            else
            {
                throw new ZFYException(result.Errors.FirstOrDefault().Description);

            }
        }
        [HttpPut]
        public async Task<IActionResult> Update([FromForm] UserUpdateModel input)
        {

            var address = JsonConvert.DeserializeObject<Address>(input.Address);

            var user = await _userManager.FindByIdAsync(HttpContext.User.Identity.GetSubjectId());

            user.Email = input.Email;
            user.NickName = input.NickName;
            user.PhoneNumber = input.PhoneNumber;
            user.UserName = input.UserName;
            user.Address = address;
            user.Signature = input.Signature;
            user.Birthday = input.Birthday;


            if (input.Avatar is not null)
            {

                if (user.Avatar.StartsWith("Uploads"))
                {
                    System.IO.File.Delete($"{user.Avatar}");
                }


                var filePath = Path.Combine("Uploads/Avatars", Guid.NewGuid().ToString() + input.Avatar.FileName.Substring(input.Avatar.FileName.LastIndexOf(".")));

                using (var fileStream = new FileStream(filePath, FileMode.Create))
                {
                    await input.Avatar.CopyToAsync(fileStream);
                }
                user.Avatar = filePath;
            }


            var result = await _userManager.UpdateAsync(user);

            if (result.Succeeded)
            {
                _logger.LogInformation("User created a new account with password.");

                await _signInManager.RefreshSignInAsync(user);

                if (Url.IsLocalUrl(input.ReturnUrl))
                {
                    return Json(input.ReturnUrl.GetReponse(true));
                }
                else if (string.IsNullOrEmpty(input.ReturnUrl))
                {
                    return Json("".GetReponse(true));
                }
                else
                {
                    // user might have clicked on a malicious link - should be logged
                    throw new ZFYException("invalid return URL");
                }
            }
            else
            {
                throw new ZFYException(result.Errors.FirstOrDefault().Description);

            }

        }
    }
}
